//
//  HMComposeTypeView.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import pop

class HMComposeTypeView: UIView {

    // 模糊的背景
    @IBOutlet weak var backgroundView: UIVisualEffectView!
    @IBOutlet weak var scrollView: UIScrollView!
    
    // 删除按钮
    @IBOutlet weak var deleteButton: UIButton!
    // 返回按钮
    @IBOutlet weak var returnButton: UIButton!
    // 分割线
    @IBOutlet weak var separatorView: UIImageView!
    
    // 删除按钮中心约束
    @IBOutlet weak var deleteButtonCenterXCons: NSLayoutConstraint!
    // 返回按钮中心约束
    @IBOutlet weak var returnButtonCenterXCons: NSLayoutConstraint!
    
    // 第一页按钮数组
    private lazy var firstPageButtons: [HMComposeButton] = [HMComposeButton]()
    
    // 第二页按钮数组
    private lazy var secondPageButtons: [HMComposeButton] = [HMComposeButton]()
    
    // 类方法加载 XIB 中的视图
    class func composeTypeView() -> HMComposeTypeView {
        return Bundle.main.loadNibNamed("HMComposeTypeView", owner: nil, options: nil)?.last as! HMComposeTypeView
    }
    
    // 从 XIB 加载到view 后
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 添加按钮
        addSubButtons()
    }
    
    // MARK: - 是有方法
    /**
     添加按钮
     */
    private func addSubButtons() {
        // 从 plist 中加载按钮
        let buttonItems = loadButtonItems()
        
        // 按钮大小
        let buttonSize = CGSize(width: 100, height: 100)
        // 按钮列数
        let maxOfColumn = 3
        
        // 计算按钮之间的间距
        let margin = (UIScreen.main.bounds.width - CGFloat(maxOfColumn) * buttonSize.width) / CGFloat(maxOfColumn + 1)
        
        // 遍历加载到的所有按钮
        for (i, buttomItem) in buttonItems.enumerated() {
            let column = i % maxOfColumn
            var row = i / maxOfColumn
            
            var offset: CGFloat = 0
            
            // 需要显示在第二页的按钮
            if i >= 6 {
                offset = UIScreen.main.bounds.width
                row -= 2
            }
            
            // 计算按钮 x
            let x = offset + (CGFloat(column) + 1) * margin + CGFloat(column) * buttonSize.width
            // 计算按钮 y
            let y = CGFloat(row) * (buttonSize.height + margin)
            
            // 创建按钮
            let button = HMComposeButton.composeTypeButton(item: buttomItem)
            
            // 设置按钮位置
            button.frame.origin = CGPoint(x: x, y: y)
            
            // 添加点击事件
            button.addTarget(self, action: #selector(buttonDidClick(button:)), for: .touchUpInside)
            
            // 添加到scrollView中
            scrollView.addSubview(button)
            
            if i >= 6 {
                // 添加到第二页按钮数组中
                secondPageButtons.append(button)
            } else {
                // 添加到第一页按钮数组中
                firstPageButtons.append(button)
            }
        }
        
        // 设置scrollView可以滚动
        scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width * 2, height: 0)
    }
    
    // 显示视图
    func show() -> Void {
        // 获取根控制器
        guard let rootView = UIApplication.shared.keyWindow?.rootViewController else {
            print("没有rootVC")
            return
        }
        
        // 将视图添加到控制器的view中
        rootView.view.addSubview(self)
        // 设置大小
        self.frame = UIScreen.main.bounds
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        self.backgroundView.pop_add(anim, forKey: "alpha")
        
        // 显示所有按钮动画
        showButtons()
    }
    
    private func showButtons() {
        // 遍历第一页的按钮
        for (i, button) in firstPageButtons.enumerated() {
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = button.center.y + 350
            anim.toValue = button.center.y
            
            anim.springBounciness = 8
            anim.springSpeed = 8
            
            // 设置动画开始时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            button.pop_add(anim, forKey: "spring")
        }
    }
    
    /**
     从plist里面加载所有按钮的信息
     - returns: 按钮
     */
    private func loadButtonItems() -> [HMComposeButtonItem] {
        let composePlist = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: composePlist) as! [[String: AnyObject]]
        
        var buttonItems = [HMComposeButtonItem]()
        for dict in array {
            buttonItems.append(HMComposeButtonItem(dict: dict))
        }
        
        return buttonItems
    }
    
    /// 点击删除按钮
    @IBAction func deleteButtonDidClick(_ sender: AnyObject) {
        // 关闭
        dismiss()
    }
    
    /// 点击返回按钮
    @IBAction func returnButtonDidClick(_ sender: AnyObject) {
        print("点击返回")
        
        // 滚动scrollView
        let offset = CGPoint(x: 0, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        // 设置约束
        returnButtonCenterXCons.constant = 0
        deleteButtonCenterXCons.constant = 0
        
        // 动画
        UIView.animate(withDuration: 0.25, animations: {
            self.separatorView.alpha = 0
            self.layoutIfNeeded()
            }) { (_) in
                self.returnButton.isHidden = true
                self.separatorView.isHidden = true
        }
    }
    
    /// 点击更多按钮
    private func showMore() {
        print("点击更多")
        
        // 滚动scrollView
        let offset = CGPoint(x: UIScreen.main.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        // 显示按钮
        returnButton.isHidden = false
        separatorView.isHidden = false
        
        // 设置约束
        returnButtonCenterXCons.constant = -60
        deleteButtonCenterXCons.constant = 60
        
        // 动画
        separatorView.alpha = 0
        UIView.animate(withDuration: 0.25) {
            self.separatorView.alpha = 1
            self.layoutIfNeeded()
        }
    }
    
    /// 类型按钮被点击
    func buttonDidClick(button: HMComposeButton) {
        // 点击了更多按钮
        if button.item!.isMore {
           showMore()
            return
        }
        
        // 获取按钮
        let views: [HMComposeButton]
        if scrollView.contentOffset.x == 0 {
            views = firstPageButtons
        } else {
            views = secondPageButtons
        }
        
        // 遍历按钮
        for (i, btn) in views.enumerated() {
            
            // 设置放大和缩小动画的值
            let scale = btn == button ? 2 : 0.5
            
            // 创建缩放动画
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.duration = 0.45
            btn.pop_add(scaleAnim, forKey: nil)
            
            // 创建透明度动画
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnim.toValue = 0.3
            alphaAnim.duration = 0.35
            
            btn.pop_add(alphaAnim, forKey: nil)
            
            // 添加动画监听
            if i == 0 {
                alphaAnim.completionBlock = { (_, _) in

                    // 动画完成后获取控制器
                    let productName = Bundle.main.infoDictionary!["CFBundleName"] as! String
                    let className = button.item?.vcName ?? ""
                    if let cls = NSClassFromString(productName + "." + className) as? UIViewController.Type {
            
                        // 创建控制器
                        let vc = cls.init()
            
                        // 弹出控制器
                        let navVC = UINavigationController(rootViewController: vc)
                        UIApplication.shared.keyWindow?.rootViewController?.present(navVC, animated: true, completion: { [weak self] () -> Void in
                                // 弹出控制器后关闭 view
                                self?.dismiss()
                            })
                    }
                }
            }
        }
        
        
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss()
    }
    
    /// 关掉当前 view
    func dismiss() -> Void {
        
        // 获取当前显示的按钮
        let views: [HMComposeButton]
        if scrollView.contentOffset.x == 0 {
            views = firstPageButtons
        } else {
            views = secondPageButtons
        }
        
        // 反过来遍历当前按钮
        for (i, button) in views.reversed().enumerated() {
            // 创建弹簧动画
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = button.center.y
            anim.toValue = button.center.y + 350
            anim.springBounciness = 8
            anim.springSpeed = 8
            
            // 设置动画时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            button.pop_add(anim, forKey: "spring")
            
            if i == 0 {
                // 监听动画完成
                anim.completionBlock = { (_, _) in
                    // 隐藏背景
                    let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
                    
                    alphaAnim.fromValue = 1
                    alphaAnim.toValue = 0
                    alphaAnim.duration = 0.25
                    
                    self.backgroundView.pop_add(alphaAnim, forKey: "alpha")
                    
                    // 监听动画完成
                    alphaAnim.completionBlock = { (_, _) in
                        // 移除当前view
                        self.removeFromSuperview()
                    }
                }
            }
        }
    }
    
}
